package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.ProjectReportService;
import com.google.project.client.Service.ProjectReportServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.client.Service.UploadService;
import com.google.project.client.Service.UploadServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectReportDTO;
import com.google.project.shared.ProjectReportDetailDTO;
import com.google.project.shared.ProjectTaskDTO;
import com.google.project.shared.UsersDTO;
import com.google.gwt.user.client.ui.Label;

public class PMCreateProjectReport extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField(provided = true)
	CellTable<ProjectTaskDTO> ctbReportTaskList = new CellTable<ProjectTaskDTO>();
	@UiField
	Button btnSaveReport;
	@UiField
	Button btnBack;
	@UiField
	DateBox dbCreatedOnDate;
	@UiField
	SimplePager pager;
	@UiField
	TextBox txtProjectName;
	@UiField FormPanel formUpload;
	@UiField FileUpload fileUpload;
	@UiField Hidden forId;
	@UiField Hidden type;
	@UiField Hidden documentName;
	@UiField Label lblDate;
	@UiField Label lblComplete;

	final MultiSelectionModel<ProjectTaskDTO> selectionModel = new MultiSelectionModel<ProjectTaskDTO>();
	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);
	private final ProjectReportServiceAsync reportSv = GWT
			.create(ProjectReportService.class);
	private final ProjectServiceAsync projectService = GWT
			.create(ProjectService.class);
	private ProjectReportDTO currReportDTO = new ProjectReportDTO();
	private final UploadServiceAsync uploadService = GWT.create(UploadService.class);
	public String  currentProjID = "";
	UsersDTO userDTO = new UsersDTO();
	List<ProjectTaskDTO> listTask = new ArrayList<ProjectTaskDTO>();
	
	interface Binder extends UiBinder<Widget, PMCreateProjectReport> {
	}
	
	public PMCreateProjectReport() {
		initWidget(binder.createAndBindUi(this));
		dbCreatedOnDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
	}
	public PMCreateProjectReport(ProjectDTO projectDTO) {
		initWidget(binder.createAndBindUi(this));
		dbCreatedOnDate.setFormat(new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
		currentProjID=projectDTO.getProjectID();
		initTable();
		getInfoUserLogin();
		getTaskByProject(currentProjID);
		txtProjectName.setText(projectDTO.getProjectName());
		dbCreatedOnDate.setValue(new Date());
		lblDate.setText("("+CommonFuntion.convertToDate(new Date(projectDTO.getStartDate()))+" - "+CommonFuntion.convertToDate(new Date(projectDTO.getDueDate()))+")");
		lblComplete.setText(projectDTO.getComplete()+" (%)");
	}
	
	
	//lấy về tất cả task theo project
	public void getTaskByProject(String projectId){
		projectService.getListTask(projectId, new AsyncCallback<List<ProjectTaskDTO>>() {

			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(List<ProjectTaskDTO> result) {
				for (ProjectTaskDTO projectTaskDTO : result) {
					if(projectTaskDTO.getParentId()==0 && projectTaskDTO.getIsMile()==0){
						listTask.add(projectTaskDTO);
					}
				}
				LoadData(listTask);
			}
		});
	}
	// get info user login from session
	public void getInfoUserLogin() {
		loginService.getCurrentUserDTO(new AsyncCallback<UsersDTO>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(UsersDTO result) {
				userDTO = result;

			}
		});
	}
	

	//khởi tạo celltable
	public void initTable() {
		// STT
		TextColumn<ProjectTaskDTO> index = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO object) {
				return object.getSTT();
			}
		};
		//Tên công việc
		TextColumn<ProjectTaskDTO> taskColumn = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO object) {
				return object.getTaskName();
			}
		};
		//Ngày bắt đầu
		TextColumn<ProjectTaskDTO> startDate = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO object) {
				return CommonFuntion.convertToDate(new Date(object.getStartDate()));
			}
		};
		//Ngày kết thúc
		TextColumn<ProjectTaskDTO> dueDate = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO object) {
				return CommonFuntion.convertToDate(new Date(object.getDueDate()));
			}
		};
		//Khối lượng ban đầu
		TextColumn<ProjectTaskDTO> amountOfWork = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO object) {
				return object.getAmountOfWork()+"("+object.getUnit()+")";
			}
		};
		//% hoàn thành
		TextColumn<ProjectTaskDTO> percent = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO object) {
				Double finish=object.getFinishedWork();
				Double amoutOfWork=object.getAmountOfWork();
				Double rate=(finish/amoutOfWork)*100 ;
				rate =rate*100;
				rate = 0d+rate.intValue();
				rate = rate/100;
				return rate+"(%)";
			}
		};
		ctbReportTaskList.setStyleName("ttable");
		ctbReportTaskList.addColumn(index, "STT");
		ctbReportTaskList.addColumn(taskColumn, "Công việc");
		ctbReportTaskList
				.addColumn(startDate, "Ngày bắt đầu");
		ctbReportTaskList.addColumn(dueDate, "Ngày kết thúc");
		ctbReportTaskList.addColumn(amountOfWork, "Khối lượng");
		ctbReportTaskList.addColumn(percent, "Hoàn thành(%)");
	}

	protected void LoadData(List<ProjectTaskDTO> taskList) {
		// SimplePager
		// pager.setDisplay(ctbUserList);
		// TODO Auto-generated method stub
		ListDataProvider<ProjectTaskDTO> dataProvider = new ListDataProvider<ProjectTaskDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbReportTaskList);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		int index=1;
		List<ProjectTaskDTO> list = dataProvider.getList();
		for (ProjectTaskDTO task : taskList) {
			task.setSTT(index+"");
			list.add(task);
			index++;
		}
		pager.setDisplay(ctbReportTaskList);
		pager.setPageSize(5);
	}
	//lưu dữ liệu vào bảng ProjectReport
	public void addProjectReport(){
		//set giá trị cho ProjectReport
		currReportDTO.setCreatedOnDate(new Date().getTime());
		currReportDTO.setFromUserID(userDTO.getUserId());
		currReportDTO.setFromUserName(userDTO.getUserName());
		currReportDTO.setProjectId(currentProjID);
		currReportDTO.setStatus(1); //người nhận chưa đọc
		//lấy giá trị từ Task đổ vào list ReportDetail
     	List<ProjectReportDetailDTO> listReportDetail=new ArrayList<ProjectReportDetailDTO>();
		if(listTask.size()>0){
			for (ProjectTaskDTO task : listTask) {
				ProjectReportDetailDTO reportDetailDTO=new ProjectReportDetailDTO();
				reportDetailDTO.setAmountOfWork(task.getAmountOfWork());
				//reportDetailDTO.setContent(taContent.getText().trim());
				reportDetailDTO.setDueDate(task.getDueDate());
				reportDetailDTO.setFinishWork(task.getFinishedWork());
				reportDetailDTO.setProjectId(task.getProjectId());
				reportDetailDTO.setStartDate(task.getStartDate());
				reportDetailDTO.setTaskId(task.getId());
				reportDetailDTO.setTaskName(task.getTaskName());
				reportDetailDTO.setUnit(task.getUnit());
				listReportDetail.add(reportDetailDTO);
				
			}
		}
		reportSv.addProjectReport(currReportDTO, currentProjID, listReportDetail, new AsyncCallback<ProjectReportDTO>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(ProjectReportDTO result) {
				uploadFile(result.getId(),"5");
				Window.alert("Gửi thành công!");
				PMEntrypoint.get().PMProjectReportList();
			}
		});
	}
	@UiHandler("btnSaveReport")
	void onBtnSaveReportClick(ClickEvent event) {
			if (Window.confirm("Bạn muốn gửi báo cáo?")) {
				addProjectReport();
			}
	}

  //upload file
	public void uploadFile(String _forId,String _type){
		//upload file
		formUpload.setEncoding(FormPanel.ENCODING_MULTIPART);
		formUpload.setMethod(FormPanel.METHOD_POST);
		forId.setDefaultValue(_forId);
		type.setDefaultValue(_type); //3-upload cho dailyReport
		uploadService.getBlobStoreUrl(new AsyncCallback<String>() {
			
			@Override
			public void onSuccess(String result) {
				formUpload.setAction(result.toString());
				formUpload.submit();
				formUpload.reset();
			}
			
			@Override
			public void onFailure(Throwable caught) {
				caught.printStackTrace();
			}
		});
		
	}


	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
		PMEntrypoint.get().PMProjectReportList();
	}

}
